package com.banmao.algorithm.No501To700.No543;

import lombok.Data;

import java.util.ArrayDeque;
import java.util.ArrayList;

public class Solution {

    // 第一个是左侧树的max，第二个是右侧树的
    private int[] max = {0, 0};

    private int result = 0;

    public int diameterOfBinaryTree(TreeNode root) {

        if(root == null) {
            return 0;
        }

        // 不是单纯的左子树深度+右子树深度，还应该遍历每个节点，把每个节点当成根
        ArrayDeque<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            int size = queue.size();

            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();

                if(poll.left != null) {
                    queue.add(poll.left);
                }

                if(poll.right != null) {
                    queue.add(poll.right);
                }


                // 遍历左子树
                int leftDepth = 0;
                recrusive(poll.left, leftDepth, max, 0);
                // 遍历右子树
                int rightDepth = 0;
                recrusive(poll.right, rightDepth, max, 1);

                if(max[0] + max[1] > result) {
                    result = max[0] + max[1];
                }
                max = new int[]{0, 0};

            }

        }

        return result;

    }

    private void recrusive(TreeNode root, int depth, int[] max, int index) {
        if (root == null) {
            return;
        }

        depth++;
        if (depth > max[index]) {
            max[index] = depth;
        }

        recrusive(root.left, depth, max, index);
        recrusive(root.right, depth, max, index);
    }

}

@Data
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
